<template>
  <div class="gu_container">
    <div class="file-list">
      <section v-for="(file, index) of files" v-if="index<=3" class="file-item draggable-item">
        <img :src="file.src" alt ondragstart="return false;">
        <span class="file-remove" @click="remove(index)">+</span>
      </section>
      <section class="file-item">
        <div @click="add" class="add">
          <span>+</span>
        </div>
      </section>
    </div>
    <input type="file" accept="image/*" @change="fileChanged" ref="file" name="file" multiple>
  </div>
</template>
<script>
export default {
  name: "fileUploader",
  data() {
    return {
      files: []
    }; // 图片数组
  },
  mounted() {},
  methods: {
    // 上传图片列表中的某个图片
    remove(index) {
      this.files.splice(index, 1);
    },
    // 添加图片操作
    add() {
      this.$refs.file.click();
    },
    // 唤醒相机/图库
    fileChanged() {
      const list = this.$refs.file.files;
      for (let i = 0; i < list.length; i++) {
        if (!this.isContain(list[i])) {
          const item = {
            size: list[i].size,
            file: list[i]
          };
          // 转换图片格式
          this.html5Reader(list[i], item);
          this.files.push(item);
          // console.log('+++++++++++++++++');
          // console.log(this.files);
        }
      }
      this.$refs.file.value = "";
    },
    // 将图片文件转成BASE64格式
    html5Reader(file, item) {
      const reader = new FileReader();
      reader.onload = e => {
        this.$set(item, "src", e.target.result);
      };
      reader.readAsDataURL(file);
    },
    // 判断是否包含
    isContain(file) {
      this.files.forEach(item => {
        if (item.size === file.size) {
          return true;
        }
      });
      return false;
    }
  }
};
</script>
<style scoped >

.file-list:after {
  content: "";
  display: block;
  clear: both;
  visibility: hidden;
  line-height: 0;
  height: 0;
  font-size: 0;
}
.file-item {
  float: left;
  position: relative;
  width: 100px;
  text-align: center;
}
.file-item img {
  width: 80px;
  height: 80px;
  border: 1px solid #ececec;
}
.file-item .file-remove {
  position: absolute;
  right: 12px;
  display: none;
  top: 4px;
  width: 14px;
  height: 14px;
  color: white;
  cursor: pointer;
  line-height: 12px;
  border-radius: 100%;
  transform: rotate(45deg);
  background: rgba(0, 0, 0, 0.5);
}
.file-item:hover .file-remove {
  display: inline;
}
.file-item .file-name {
  margin: 0;
  height: 40px;
  word-break: break-all;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
.add {
  width: 80px;
  height: 80px;
  margin-left: 10px;
  float: left;
  text-align: center;
  line-height: 80px;
  background-color: #f2f2f2;
  font-size: 30px;
  cursor: pointer;
}
input {
  display: none;
}
</style>


